package com.ly.security;

import com.google.common.base.Objects;
import com.ly.base.LoginUserUtil;
import com.ly.entity.User;
import com.ly.service.ISmsService;
import com.ly.service.IUserService;
import joptsimple.internal.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：LY
 * @date ：Created in 2020/11/25 15:14
 * @modified By：
 */
public class AuthFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    private IUserService userService;

    @Autowired
    private ISmsService smsService;

//    @Override
//    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
//
//        super.unsuccessfulAuthentication(request, response, failed);
//        System.out.println("新uri======"+request.getRequestURI());
//    }

    /**
     * 尝试验证逻辑
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
       String name = obtainUsername(request);
       if (!Strings.isNullOrEmpty(name)){
           //用户名不为空则为用户名密码登录 无需验证码
           request.setAttribute("username",name);
           return super.attemptAuthentication(request,response);
       }
        String telephone = request.getParameter("telephone");
        if (Strings.isNullOrEmpty(telephone)|| !LoginUserUtil.checkTelephone(telephone)){
            throw new BadCredentialsException("Wrong telephone number");
        }
        User user = userService.findUserByTelephone(telephone);

        String smsCode = request.getParameter("smsCode");
        String sessionCode =  smsService.getSmsCode(telephone);
        if (Objects.equal(smsCode,sessionCode)){
            if (user==null){
                //注册
                user=userService.addUserByPhone(telephone);
            }
            return new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities());
        }else{
            throw new BadCredentialsException("smsCodeError");
        }
    }
}
